﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using ZeroSum.Domain.UnitOfWork;

namespace ZeroSum.App.Middlewares;

/// <summary>
///     自动提交数据库改动中间件
/// </summary>
public class AutoSaveMiddleware
{
    private readonly RequestDelegate _next;

    public AutoSaveMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var unitOfWork = context.RequestServices.GetService<IUnitOfWork>();
        await _next(context);
        await unitOfWork?.SaveChangesAsync()!;
    }
}

public static class AutoSaveMiddlewareExtensions
{
    /// <summary>
    ///     启用自动提交数据库改动中间件
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static IApplicationBuilder EnableAutoSave(this IApplicationBuilder app)
    {
        app.UseMiddleware<AutoSaveMiddleware>();
        return app;
    }
}